package basic;

import java.nio.ByteBuffer;

/**
 * @author： pang-yun
 * @date： 2021-08-30 19:10
 * 功能目的 ：用于 黏包  半包
 */

public class HalfString {

    public static void main(String[] args) {
        ByteBuffer source = ByteBuffer.allocate(128);
        source.put("Hello,\nWorld!\nI am Herman pang\nHo".getBytes());
        split(source);
        System.out.println("------------------------------");
        source.put("w are you!\n".getBytes());
        split(source);

    }

    public static void split(ByteBuffer buffer) {
        buffer.flip();
        for (int i=0;i<buffer.limit();i++){
            if (buffer.get(i)=='\n'){
                int length = i+1-buffer.position();
                ByteBuffer allocate = ByteBuffer.allocate(length);
                for (int j=0;j<length;j++){
                    allocate.put(buffer.get(j));
                }
                read(allocate, length);
            }
        }
        buffer.compact();
    }

    public static void read(ByteBuffer buffer,int length) {
        buffer.flip();
        for (int i=0;i<length;i++){
            System.out.print((char) buffer.get(i));
        }
    }
}


